import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

const defaultLimit = 50
const startPage = 0

export default function useQuery({ fetcher, pageSize = defaultLimit }) {
    const isLoading = ref(false)
    const currentPage = ref(startPage - 1)
    const data = ref([])
    const isFetchingNextPage = ref(false)
    const hasNextPage = ref(true)

    function refetch() {
        isLoading.value = false
        currentPage.value = startPage - 1
        isFetchingNextPage.value = false
        hasNextPage.value = true
        fetchNextPage()
    }

    async function fetchNextPage() {
        if (isFetchingNextPage.value || !hasNextPage.value) {
            return
        }

        if (currentPage.value <= startPage - 1) {
            isLoading.value = true
        } else {
            isFetchingNextPage.value = true
        }
        try {
            const resp = await fetcher({
                page: currentPage.value + 1,
                limit: pageSize,
            })
            isFetchingNextPage.value = false
            isLoading.value = false

            const newData =
                currentPage.value + 1 === 0
                    ? [...resp.content]
                    : [...data.value, ...resp.content]
            if (resp.totalElements > newData.length) {
                hasNextPage.value = true
            } else {
                hasNextPage.value = false
            }
            data.value = newData
            currentPage.value++
        } catch (e) {
            /*empty*/
        }
    }

    onLoad(async () => {
        refetch()
    })

    return {
        data,
        fetchNextPage,
        isLoading,
        isFetchingNextPage,
        hasNextPage,
        refetch,
    }
}
